package com.wootion.cims.module.systemsetting.community.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wootion.cims.dao.*;
import com.wootion.cims.general.utils.GetIp;
import com.wootion.cims.module.systemsetting.community.model.SysCommunity;
import com.wootion.cims.module.systemsetting.community.service.SysCommunityService;
import com.wootion.cims.module.systemsetting.log.model.SysLog;
import com.wootion.cims.module.systemsetting.polt.model.SysPlot;
import com.wootion.cims.module.systemsetting.user.model.SysUserRole;
import com.wootion.cims.module.systemsetting.user.model.User;
import com.wootion.cims.response.ResponseResult;
import com.wootion.cims.response.ResultCode;
import com.wootion.cims.shiro.utils.ShiroUtils;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author: LanQiang
 * @Date: 2022/11/21/11:27
 * @Description: 作用xxx
 */
@Service
public class SysCommunityServiceImpl implements SysCommunityService {
    @Resource
    private SysCommunityDao sysCommunityDao;
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private SysUserCommunityDao sysUserCommunityDao;
    @Resource
    private SysUserRoleDao sysUserRoleDao;
    @Resource
    private SysPlotDao sysPlotDao;

    /**
     * 查询所有社区信息/或条件查询,并分页返回
     *
     * @param condition
     * @param limit
     * @param page
     * @return
     */
    @Override
    public ResponseResult list(String condition, Integer page, Integer limit) {
        
        //获取当前登陆人的信息
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper5.eq(SysUserRole::getUserId,user.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(lambdaQueryWrapper5);
        String roleKey = sysRoleDao.findByRoles(sysUserRole.getRoleId());
        if ("street:admin".equals(roleKey)) {
            LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(StringUtils.hasText(condition), SysCommunity::getName, condition);
            lambdaQueryWrapper.eq(SysCommunity::getEnable, true);
            lambdaQueryWrapper.orderByDesc(SysCommunity::getCreateTime);
            IPage<SysCommunity> page1 = new Page<>(page, limit);
            IPage<SysCommunity> communityPage = sysCommunityDao.selectPage(page1, lambdaQueryWrapper);
            return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).data(communityPage).build();
        }
        //不是街道管理员，只能看到自己管辖的社区信息
        List<String> commnityIds = sysUserCommunityDao.commnityIds(user.getId());
        List<SysCommunity> communities = sysCommunityDao.findByCommunity(commnityIds);
        List<String> ids = new ArrayList<>();
        for (SysCommunity community : communities) {
            ids.add(community.getId());
        }
        LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasText(condition), SysCommunity::getName, condition);
        lambdaQueryWrapper.eq(SysCommunity::getEnable, true);
        lambdaQueryWrapper.in(ids.size() > 0, SysCommunity::getId, ids);
        lambdaQueryWrapper.orderByDesc(SysCommunity::getCreateTime);
        IPage<SysCommunity> page1 = new Page<>(page, limit);
        IPage<SysCommunity> communityPage = sysCommunityDao.selectPage(page1, lambdaQueryWrapper);
        return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).data(communityPage).build();
    }

    /**
     * 修改社区
     * @param sysCommunity
     * @return
     */
    @Override
    public ResponseResult update(SysCommunity sysCommunity) {
        String name = sysCommunity.getName();
        String newName = name.replace(" ", "");
        sysCommunity.setName(newName);
        //如果id不为空，则是修改
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        if (StringUtils.hasText(sysCommunity.getId())) {
            LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper4 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper4.eq(SysCommunity::getId,sysCommunity.getId());
            SysCommunity sysCommunity1 = sysCommunityDao.selectOne(lambdaQueryWrapper4);

            LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper5.eq(SysCommunity::getName,sysCommunity.getName());
            SysCommunity sysCommunity2 = sysCommunityDao.selectOne(lambdaQueryWrapper5);

            if(Objects.isNull(sysCommunity2) || sysCommunity1.getId().equals(sysCommunity2.getId())){
                sysCommunity.setUpdateTime(new Date());
                sysCommunity.setEnable(true);
                sysCommunity.setUpdateUserid(user.getId());
                int rows = sysCommunityDao.updateById(sysCommunity);
                return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
            }
            LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(StringUtils.hasText(sysCommunity.getName()), SysCommunity::getName, sysCommunity.getName());
            //更新之前校验社区名称不能重复
            if (sysCommunityDao.exists(lambdaQueryWrapper)) {
                return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message(ResultCode.NAME_EXITS_ERROR.getMessage()).build();
            }
        }
        //id为空，代表新增
        LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasText(sysCommunity.getName()), SysCommunity::getName, sysCommunity.getName());
        //社区名称不能重复校验
        if (sysCommunityDao.exists(lambdaQueryWrapper)) {
            return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message(ResultCode.NAME_EXITS_ERROR.getMessage()).build();
        }
        sysCommunity.setEnable(true).setCreateTime(new Date()).setCreateUserid(user.getId());
        int rows = sysCommunityDao.insert(sysCommunity);
        return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
    }

    /**
     * 新增社区
     * @param sysCommunity
     * @return
     */
    @Override
    public ResponseResult save(SysCommunity sysCommunity) {
        String name = sysCommunity.getName();
        String newName = name.replace(" ", "");
        sysCommunity.setName(newName);
        //如果id不为空，则是修改
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        if (StringUtils.hasText(sysCommunity.getId())) {
            LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper4 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper4.eq(SysCommunity::getId,sysCommunity.getId());
            SysCommunity sysCommunity1 = sysCommunityDao.selectOne(lambdaQueryWrapper4);

            LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper5.eq(SysCommunity::getName,sysCommunity.getName());
            SysCommunity sysCommunity2 = sysCommunityDao.selectOne(lambdaQueryWrapper5);

            if(Objects.isNull(sysCommunity2) || sysCommunity1.getId().equals(sysCommunity2.getId())){
                sysCommunity.setUpdateTime(new Date());
                sysCommunity.setEnable(true);
                sysCommunity.setUpdateUserid(user.getId());
                int rows = sysCommunityDao.updateById(sysCommunity);
                return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
            }
            LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(StringUtils.hasText(sysCommunity.getName()), SysCommunity::getName, sysCommunity.getName());
            //更新之前校验社区名称不能重复
            if (sysCommunityDao.exists(lambdaQueryWrapper)) {
                return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message(ResultCode.NAME_EXITS_ERROR.getMessage()).build();
            }
        }
        //id为空，代表新增
        LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasText(sysCommunity.getName()), SysCommunity::getName, sysCommunity.getName());
        //社区名称不能重复校验
        if (sysCommunityDao.exists(lambdaQueryWrapper)) {
            return ResponseResult.builder().code(ResultCode.NAME_EXITS_ERROR.getCode()).message(ResultCode.NAME_EXITS_ERROR.getMessage()).build();
        }
        sysCommunity.setEnable(true).setCreateTime(new Date()).setCreateUserid(user.getId());
        int rows = sysCommunityDao.insert(sysCommunity);
        return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
    }

    /**
     * 删除社区
     *
     * @param sysCommunity
     */
    public ResponseResult deleteCommunity(SysCommunity sysCommunity) {
        if (StringUtils.hasText(sysCommunity.getId())) {
            //当前社区下，小区数量为0的时候，可以删除
            LambdaQueryWrapper<SysPlot> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysPlot::getEnabled,true);
            queryWrapper1.eq(SysPlot::getCommunityId,sysCommunity.getId());
            List<SysPlot> sysPlots = sysPlotDao.selectList(queryWrapper1);
            if(sysPlots.size()>0){
                return ResponseResult.builder().message("当前社区下，关联的有小区不能删除").code(ResultCode.SYSTEM_ERROR.getCode()).build();
            }
            sysCommunity.setEnable(false);
            int rows = sysCommunityDao.updateById(sysCommunity);
            return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
        return ResponseResult.builder().code(ResultCode.PARAM_IS_BLANK.getCode()).message(ResultCode.PARAM_IS_BLANK.getMessage()).build();
    }
}
